package com.biaobiaoqi.scoreanalysis.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.tools.javac.util.FatalError;

/**
 * An abstraction of different encrypt strategy implementation. If you want to
 * create a new encrypt strategy, implement it.
 * 
 * @author DJ
 * 
 */
public class StandardMD5EncryptStrategy implements EncryptStrategy{
	private static final Log log = LogFactory.getLog(StandardMD5EncryptStrategy.class);
	public String encryptPassword(String password) {
		try {
			log.debug("encrypt password.");
			MessageDigest mDigest = MessageDigest.getInstance("MD5");
			mDigest.update(password.getBytes());
			byte[] binhashedPassword = mDigest.digest();
			String hashedPassword = byte2hex(binhashedPassword);
			log.debug("encrypt success.");
			return hashedPassword;
		} catch (NoSuchAlgorithmException e) {
			log.error("encript failed:"+e.getMessage());
			throw new FatalError("cannot find encrypt algorithm: MD5");
		} catch (RuntimeException e) {
			log.error("encrypt failed:"+e.getMessage());
			throw e;
		}
	}

	private static String byte2hex(byte[] b)  
	{
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + "0" + stmp;
			else
				hs = hs + stmp;
		}
		return hs.toLowerCase();
	}

}
